package com.socket.tools.service;

import com.socket.tools.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 心跳服务 - 管理连接健康状态
 */
@Service
public class HeartbeatService {
    
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatService.class);
    
    @Autowired
    private ConnectionManager connectionManager;
    
    private final ConcurrentHashMap<String, Long> lastHeartbeat = new ConcurrentHashMap<>();
    private final AtomicInteger heartbeatCount = new AtomicInteger(0);
    
    /**
     * 发送心跳包
     */
    public void sendHeartbeat(WebSocketSession session) {
        try {
            if (session != null && session.isOpen()) {
                String heartbeatMsg = "{\"type\":\"HEARTBEAT\",\"timestamp\":" + System.currentTimeMillis() + "}";
                session.sendMessage(new TextMessage(heartbeatMsg));
                lastHeartbeat.put(session.getId(), System.currentTimeMillis());
                heartbeatCount.incrementAndGet();
            }
        } catch (IOException e) {
            logger.warn("发送心跳包失败: {}", e.getMessage());
        }
    }
    
    /**
     * 处理心跳响应
     */
    public void handleHeartbeatResponse(String sessionId) {
        lastHeartbeat.put(sessionId, System.currentTimeMillis());
    }
    
//    /**
//     * 定期清理无效连接 (每30秒执行一次)
//     */
//    @Scheduled(fixedRate = 30000)
//    public void cleanupInactiveConnections() {
//        long currentTime = System.currentTimeMillis();
//        long timeout = 60000; // 1分钟超时
//
//        // 清理超时的心跳
//        lastHeartbeat.entrySet().removeIf(entry ->
//            currentTime - entry.getValue() > timeout
//        );
//
//        logger.info("心跳清理完成，当前活跃连接数: {}", lastHeartbeat.size());
//    }
//


    /**
     * 定期清理无效连接
     */
    @Scheduled(cron = "0 0 1 * * ? ")
    public void cleanupInactiveConnections() {
        Message clearAllMsg = new Message();
        clearAllMsg.setType(Message.MessageType.CLEAR_ALL);
        connectionManager.broadcastToAdmins(clearAllMsg);
        connectionManager.broadcastToClient(clearAllMsg);

        try {
            Thread.sleep(1000*60);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        connectionManager.clearAllSessions();

    }

    /**
     * 定期发送心跳包 (每10秒执行一次)
     */
    @Scheduled(fixedRate = 10000)
    public void sendHeartbeats() {
        // 向所有活跃的服务端用户发送心跳
        connectionManager.getAdminSessions().forEach((adminId, session) -> {
            sendHeartbeat(session);
        });
        
        // 向所有活跃的客户端发送心跳
        connectionManager.getClientSessions().forEach((clientId, session) -> {
            sendHeartbeat(session);
        });
        
        logger.debug("心跳包发送完成，总数: {}", heartbeatCount.get());
    }
    
    /**
     * 获取心跳统计信息
     */
    public ConcurrentHashMap<String, Object> getHeartbeatStats() {
        ConcurrentHashMap<String, Object> stats = new ConcurrentHashMap<>();
        stats.put("activeConnections", lastHeartbeat.size());
        stats.put("totalHeartbeats", heartbeatCount.get());
        stats.put("lastCleanup", System.currentTimeMillis());
        return stats;
    }
} 
